<template>
  <div class="promission">
    <a-form layout="inline" :form="form" @submit="handleSearch">

      <!-- <a-form-item label="用户ID:" >
      <a-input v-decorator="['userId']" ></a-input>
    </a-form-item> -->

      <a-form-item label="手机号:">
        <a-input v-decorator="['phone']">

        </a-input>
      </a-form-item>

      <a-form-item label="状态：">
        <a-radio-group v-decorator="['isEnable']" :options="plainOptions" />
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit">
          查询
        </a-button>
      </a-form-item>

    </a-form>
    <a-table style="margin-top:20px" :loading="loading" :columns="columns" :data-source="dataSource" :pagination="{
        current: page,
        pageSize: pageSize,
        total: total,
        showSizeChanger: true,
        showLessItems: true,
        showQuickJumper: true,
        showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
        onChange: onPageChange,
        onShowSizeChange: onSizeChange,
          }" rowKey="id">
      <template slot="endTime" slot-scope="text, record">
        <span>{{ $moment(new Date(record.endTime)).format("YYYY-MM-DD HH:mm:ss")}}</span>
      </template>

      <div v-if="record.editable" slot="roleId" slot-scope="text, record ,index">
        <a-select v-model="record.role" @change="(e) => handleChange(e, index)" style="width: 100%"
          placeholder="请选择角色">
          <a-select-option v-for="(i,index) in roleList" :key="index" :value="i.id">
            {{ i.role }}
          </a-select-option>
        </a-select>
      </div>
      <span v-else slot="roleId" slot-scope="text">
        {{ changeTranslate(text) }}
      </span>
      
      <span slot="authList" slot-scope="text, record">
        <a-tag v-for="(item,index) in record.authList" :key="index">{{translateAuth[item]}}</a-tag>
      </span>

      <template slot="action" slot-scope="text, record ,index">
        <span v-if="record.editable" style="margin-right:10px">
          <a @click="() => save(record)" style="margin-right:10px">保存</a>
          <a-popconfirm title="确定取消?" @confirm="() => cancel(index, text)">
            <a>取消</a>
          </a-popconfirm>
        </span>
        <span v-else style="margin-right:10px">
          <a :disabled="editingKey !== ''" @click="() => edit(index)">修改</a>
        </span>

        <span>
          <a @click="showSetting(record)">设置</a>
        </span>
      </template>

    </a-table>

    <a-modal
      title="Title"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="submitSetting"
      @cancel="visible = false"
    >
      <a-form-model
        :model="settingForm" 
        :label-col="{ span: 6 }" 
        :wrapper-col="{ span: 14 }"
      >
        <a-form-model-item label="启用">
          <a-switch v-model="settingForm.isEnable" />
        </a-form-model-item>
        <a-form-model-item label="允许矿机数量">
          <a-input-number v-model="settingForm.millNums" />
        </a-form-model-item>
        <a-form-model-item label="截止时间">
          <a-date-picker
            :mode="mode1"
            v-model="settingForm.endTime"
            show-time
            @openChange="handleOpenChange1"
            @panelChange="handlePanelChange1"
            @change="onChange"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
  import {
    mapState
  } from 'vuex'
  import {
    translateAuth
  } from '../../utils/util'
  import {
    getUserList,
    userRole,
    userManage
  } from '@/services/user.js'
    import {
    getRoleList,
  } from '@/services/promission.js'
  import moment from 'moment'
  export default {
    name: 'Promission',
    components: {},
    computed: {
      ...mapState('setting', ['pageMinHeight']),
    },
    data() {
      this.dateFormat = 'YYYY-MM-DD HH:mm:ss';
      return {
        mode1: 'date',
        moment,
        visible: false,
        confirmLoading: false,
        editingKey: '',
        page: 1,
        pageSize: 10,
        total: 1,
        loading: false,
        translateAuth, // 权限对应数组
        form: this.$form.createForm(this, {
          name: 'advanced_search'
        }),
        userId: JSON.parse(localStorage.getItem('admin.user')).userId,
        phone: null,
        isEnable: null,
        plainOptions: [{
            label: '可用',
            value: '1'
          },
          {
            label: '待审核',
            value: '-1'
          },
          {
            label: '禁用',
            value: '0'
          },
          {
            label: '全部',
            value: null
          }
        ],
        columns: [{
            title: '用户角色',
            dataIndex: 'roleId',
            key: 'roleId',
            scopedSlots: {
              customRender: 'roleId'
            },
          },
          {
            title: '用户昵称',
            dataIndex: 'username',
            key: 'username',
          },
          {
            title: '用户密码',
            dataIndex: 'password',
            key: 'password',
          },
          {
            title: '手机号码',
            dataIndex: 'phone',
            key: 'phone',
          },
          {
            title: '可使用矿机数',
            dataIndex: 'millNums',
            key: 'millNums',
          },
          {
            title: '用户使用期限',
            dataIndex: 'endTime',
            key: 'endTime',
            scopedSlots: {
              customRender: 'endTime'
            },
          },
          {
            title: '角色权限列表',
            dataIndex: 'authList',
            key: 'authList',
            scopedSlots: {
              customRender: 'authList'
            },
          },
          {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            width: 160,
            scopedSlots: {
              customRender: 'action'
            },
          },
        ],
        dataSource: [],
        roleList: [],
        translateObj: {},
        settingForm: {
          userId: '',
          isEnable: false,
          millNums: 0,
          endTime: ''
        }
      }
    },
    mounted() {
      this.getRole()
      this.getRoleTableData()
    },
    methods: {
      handleSearch(e) {
        this.form.validateFields((error, values) => {
          console.log('Received values of form: ', values);
          // this.userId = values.userId
          this.phone = values.phone
          this.isEnable = values.isEnable
          this.getRoleTableData()
        });
      },
      /**
       * 查询表格
       */
      getRoleTableData() {
        this.loading = true
        let formData = new FormData()
        if (this.phone) formData.append('phone', this.phone)
        if (this.isEnable) formData.append('isEnable', this.isEnable)

        formData.append('userId', this.userId)
        formData.append('pageNum', this.page)
        formData.append('pageSize', this.pageSize)

        getUserList(formData).then(res => {
          this.loading = false
          this.dataSource = res.data.result.list.map(item => {
            item.editable = false
            item.authList = item.authList.map(item => Number(item))
            return item
          })
          this.total = res.data.result.total
        })
      },
      /**
       * @desc 获取角色列表
       */
      getRole() {
        let formData = new FormData()
        formData.append('userId', this.userId)
        getRoleList(formData).then(res => {
          this.roleList = res.data.result
          this.translateUser()
        })
      },
      /**
       * @desc 翻译角色
       */
      translateUser() {
        let array = this.roleList
        let obj = {}
        for(let i = 0; i < array.length; i ++) {
          obj[array[i].id] = array[i].role
        }
        console.log(obj, '什么TMD叫惊喜！！')
        this.translateObj = obj
      },
      changeTranslate(e) {
        return this.translateObj[e]
      },
      onSizeChange(current, size) {
        this.page = 1
        this.pageSize = size
        this.getRoleTableData()
      },
      onPageChange(page, pageSize) {
        this.page = page
        this.pageSize = pageSize
        this.getRoleTableData()
      },
      //表格角色修改
      handleChange(e, index) {
        console.log(e, index, ',,,,,,,,,,,,,,,,./');
      },
      // 修改按钮
      edit(key) {
        this.dataSource[key].editable = true
        this.editingKey = key;
      },
      // 修改角色
      save(record) {
        console.log(record, '保存')
        let formData = new FormData()
        formData.append('userId', record.userId)
        formData.append('adminId', this.userId)
        formData.append('roleId', record.role)
        userRole(formData).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.result);
            this.getRoleTableData()
            this.editingKey = '';
          } else {
            this.$message.error(res.result);
          }
        })
      },
      cancel(key) {
        this.dataSource[key].editable = false
        this.editingKey = '';
      },
      showSetting(record) {
        this.visible = true
        console.log(record)
        this.settingForm.userId = record.userId
        this.settingForm.isEnable = record.isEnable ? true : false
        this.settingForm.millNums = record.millNums
        this.settingForm.endTime = moment(record.endTime).format('YYYY-MM-DD HH:mm:ss')
      },
      submitSetting() {
        this.confirmLoading = true
        let formData = new FormData()
        formData.append('userId', this.settingForm.userId)
        formData.append('adminId', this.userId)
        formData.append('isEnable', this.settingForm.isEnable == true ? '1' : '0')
        formData.append('millNums', this.settingForm.millNums)
        formData.append('endTime', this.settingForm.endTime)
        userManage(formData).then(res => {
          if(res.data.code == 200) {
            this.$message.success(res.data.result)
            this.confirmLoading = false
            this.visible = false
            this.getRoleTableData()
          } else {
            this.$message.error(res.data.result)
            this.confirmLoading = false
          }
        })
      },
      handleOpenChange1(open) {
        if (open) {
          this.mode1 = 'time';
        }
      },
      handlePanelChange1(value, mode) {
        this.mode1 = mode;
      },
      onChange(date, dateString) {
        console.log(date, dateString);
        this.settingForm.endTime = dateString
      }
    }
  }
</script>

<style scoped lang="less">
  .promission {
    background-color: @base-bg-color;
    padding: 24px;
  }
</style>